package com.njbw.rateLimit;

import java.util.Random;

/**
 * 固定时间窗口限流
 * 计数器
 *
 * @author 黄侯淳
 * @since JDK 1.8
 */
public class Counter {

    // 时间窗口
    private final int interval = 1000;

    // 时间窗口内的阈值
    private final int limit = 5;

    private long lastTime = System.currentTimeMillis();

    private int counter = 0;

    public boolean tryAcquire() {
        if (System.currentTimeMillis() < lastTime + interval) {
            // 在时间窗口内
            counter++;
        } else {
            // 超过时间窗口重置 counter
            lastTime = System.currentTimeMillis();
            counter = 0;
        }
        return counter < limit;
    }

    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        while (true) {
            if (counter.tryAcquire()) {
                System.out.println("请求成功...");
            } else {
                System.out.println("限流了...");
            }
            Thread.sleep(100 * new Random().nextInt(5));
        }
    }
}
